package com.atguigu.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.springframework.jdbc.core.RowMapper;

/**
 * 把查询的结果封装成map集合
 * 
 * @author nrzt
 *
 */
public class BaseRowMapper implements RowMapper<Map<String, Object>> {

	@Override
	public Map<String, Object> mapRow(ResultSet rs, int rowNum)  {

		Map<String, Object> map = new HashMap<>();
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			int columnCount = rsmd.getColumnCount();
			for (int i = 1; i <= columnCount; i++) {
				String columnName = rsmd.getColumnLabel(i);
				Object columnValue = null;
				if (rsmd.getColumnTypeName(i).equals("BLOB")) {
					InputStream is = rs.getBinaryStream(i);
					columnValue = is;    
				} else if (rsmd.getColumnTypeName(i).contains("CLOB")) {
					Reader r=rs.getCharacterStream(i);
					StringBuffer buffer = new StringBuffer("");
					if(r!=null) {
						BufferedReader in = new BufferedReader(r);
						String line = "";
						while ((line = in.readLine()) != null){
						     buffer.append(line); 
						}
					}
					columnValue=buffer.toString();
				} else if (rsmd.getColumnTypeName(i).contains("TIMESTAMP")) {
					Calendar calender = Calendar.getInstance();
					Timestamp t = rs.getTimestamp(i, calender);
					columnValue = t;
				} else {
					columnValue = rs.getObject(columnName);
				}
				map.put(columnName, columnValue);
			}
		} catch (SQLException e) {	 e.printStackTrace();} 
		catch (IOException e) { e.printStackTrace(); }
			 
		map.remove("RN");
		return map;
	}

}
